import {
  ref,
  defineComponent,
  reactive,
  onMounted,
  onBeforeMount,
  onUnmounted,
} from 'vue'
import {
  ElButton as Button,
  ElMessage as message,
  ElMessageBox as messageBox,
  ElFormItem as FormItem,
  ElInput as Input,
} from 'element-plus'
import type { DevicesData } from '@/types/views/devices'
import { getApi } from '@/api/views/devices/list'
import type { FormInstance } from 'element-plus'
import { formatDate } from '@/utils'
import searchListFun from './config/search'
import { default as columnsFunc } from './config/columns'
import {
  default as formListFunc,
  publicStr as dialogPublicStr,
} from './config/dialog'
import socket from '@/utils/socket'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  name: 'userList',
  setup() {
    const { t } = useI18n()
    const messageData = ref('')
    const receive = (message: any) => {
      console.log('message', message.data)
      messageData.value = message.data
    }

    onBeforeMount(() => {
      socket.init(receive)
    })
    onUnmounted(() => {
      socket.close()
    })

    // 搜索栏
    const searchParams = ref({})
    const onChangeSearch = (params: any) => {
      searchParams.value = params
      fetchData()
    }

    // 表格
    const tableData = ref<DevicesData[] | null>(null)
    const handleSelectionChange = (val: DevicesData[]) => {
      console.log('val', val)
    }
    onMounted(() => {
      fetchData()
    })
    const fetchData = async () => {
      const res = await getApi({
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      })
      tableData.value = res as DevicesData[]
      pagination.total = 200
    }

    const handeEdit = (row: any) => {
      showModal('edit', row)
    }
    const handleDel = (id: number) => {
      messageBox
        .confirm(t('messageBox.deletePrompt'), t('messageBox.tips'), {
          icon: (
            <>
              <i class="iconfont icon-jinggao"></i>
            </>
          ),
          confirmButtonText: t('messageBox.determine'),
          cancelButtonText: t('messageBox.cancel'),
          type: 'warning',
        })
        .then(() => {
          setTimeout(() => {
            message({
              type: 'success',
              message: t('messageBox.deleteSucceeded'),
            })
          }, 300)
        })
        .catch(() => {
          message({
            type: 'info',
            message: t('messageBox.undelete'),
          })
        })
    }

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0,
    })

    const handleCurrentChange = (currentPage: any) => {
      pagination.currentPage = currentPage
      fetchData()
    }
    const handleSizeChange = (val: number) => {
      pagination.pageSize = val
      fetchData()
    }
    // 对话框
    const handleFormInline = reactive<DevicesData<undefined, undefined, any>>({
      id: undefined,
      name: undefined,
      date: undefined,
      address: undefined,
      gender: 0,
      hobby: undefined,
      city: [],
      active: true,
    })

    const dialogConfig = reactive({
      // width: '800px',
      dialogVisible: false,
      draggable: true,
      // closeOnClickModal: false,
      beforeClose: () => (dialogConfig.dialogVisible = false),
    })
    const formConfig = reactive({
      ref: 'formRef',
      formInline: handleFormInline,
    })
    const formItemConfig = reactive({
      title: t('dialog.newData'),
      formList: formListFunc(t),
    })

    const handleSubmit = async (formEl: FormInstance | undefined, loading: { value: boolean }) => {
      if (!formEl) {
        return
      }
      await formEl.validate((valid, fields: any) => {
        if (valid) {
          setTimeout(() => {
            console.log('handleFormInline', handleFormInline);
            console.table('fields', fields);
            const date = formatDate((handleFormInline.date as Date).getTime())
            const params = {
              date,
            }
            console.log('params', params)
            dialogRefreshTable()
            loading.value = false;
            dialogConfig.dialogVisible = false
          }, 1000)
        } else {
          loading.value = false;
        }
      })
    }

    const showModal = (type: string, record?: DevicesData) => {
      dialogConfig.dialogVisible = true
      formItemConfig.title =
        type === 'add' ? t('dialog.newData') : t('dialog.editData')
      if (type == 'edit') {
        Object.keys(handleFormInline).map(
          (key) =>
          (handleFormInline[key as keyof typeof handleFormInline] =
            record && record[key as keyof typeof record])
        )
        handleFormInline.date = new Date(
          handleFormInline.date as keyof typeof handleFormInline
        )
      } else {
      }
    }

    const handleAdd = () => {
      showModal('add')
    }
    const dialogRefreshTable = () => { }

    const $slots = {
      handleExtra: () => (
        <div>
          <Button type="primary" onClick={handleAdd}>
            {t('button.newlyAdded')}
          </Button>
          <Button type="primary">{t('button.export')}</Button>
          <Button type="primary">{t('button.upload')}</Button>
        </div>
      ),
      dialogExtra: () => (
        <>
          <FormItem
            label={t(`${dialogPublicStr}id`)}
            prop="id"
            rules={[
              {
                required: true,
                message: t(`${dialogPublicStr}idTips`),
                trigger: 'blur',
              },
            ]}
          >
            <Input
              clearable
              v-model={handleFormInline.id}
              placeholder={t(`${dialogPublicStr}idTips`)}
            />
          </FormItem>
        </>
      ),
    }

    return () => (
      <>
        {/* <p>{messageData.value}</p> */}
        <s-design
          v-slots={$slots}
          searchList={searchListFun()}
          onChangeSearch={onChangeSearch}
          handleSelectionChange={handleSelectionChange}
          data={tableData.value}
          columns={columnsFunc(handeEdit, handleDel, t)}
          pagination={pagination}
          handleCurrentChange={handleCurrentChange}
          handleSizeChange={handleSizeChange}
          dialogConfig={dialogConfig}
          formConfig={formConfig}
          formItemConfig={formItemConfig}
          handleSubmit={handleSubmit}
        />
      </>
    )
  },
})
